<template>
	<el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
		<el-form-item label="旧密码" prop="oldPassword">
			<el-input v-model.trim="form.oldPassword" clearable show-password type="password"/>
		</el-form-item>
		<el-form-item label="新密码" prop="newPassword">
			<el-input v-model.trim="form.newPassword" clearable show-password type="password"/>
		</el-form-item>
		<el-form-item label="确认新密码" prop="newPasswordAgain">
			<el-input v-model.trim="form.newPasswordAgain" clearable show-password type="password"/>
		</el-form-item>
		<el-form-item>
			<template #label></template>
			<el-button :loading="loading" icon="el-icon-CircleCheck" type="primary" @click="submit">确认</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>

import {updateMyPasswordApi} from '@/api/system/myself.api'
import {useUserStore} from '@/stores/modules/user.store'
import {reactive, ref} from 'vue'
import {focusFormErrorElement, messageSuccess} from '@/utils/commonUtil'
import type {FormInstance, FormRules} from 'element-plus'
import type {RuleItemValidator} from '@/model/global-import'

const userStore = useUserStore()

const formRef = ref<FormInstance>()

const loading = ref(false)

const form = reactive({
	oldPassword: '',
	newPassword: '',
	newPasswordAgain: ''
})

const validateNewPasswordAgain: RuleItemValidator = (rule, value, callback, source, options) => {
	if (value === form.newPassword) {
		callback()
	} else {
		callback(Error())
	}
}

const rules = reactive<FormRules>({
	oldPassword: [
		{required: true, message: '请输入旧密码', trigger: 'change'}
	],
	newPassword: [
		{required: true, message: '请输入新密码', trigger: 'change'},
		{min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'change'}
	],
	newPasswordAgain: [
		{
			required: true,
			message: '两次输入的密码不一致',
			trigger: 'change',
			validator: validateNewPasswordAgain
		}
	]
})

const submit = () => {
	formRef.value!.validate(isValid => {
		if (isValid) {
			loading.value = true
			const data: UpdateMyPasswordRequest = {
				userId: userStore.userId!,
				oldPassword: form.oldPassword,
				newPassword: form.newPassword
			}
			updateMyPasswordApi(data).then(() => {
				messageSuccess('密码已修改')
				formRef.value!.resetFields()
			}).finally(() => {
				loading.value = false
			})
		} else {
			focusFormErrorElement()
		}
	})
}
</script>
